package com.py.gs.tools;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

/**
 * 
 * 2018年11月6日
 *
 */
public class IPTools {

	/**
	 * 获取本机ipv4地址
	 * @return
	 * @throws SocketException
	 */
    public static String getHostIP() throws SocketException {
		Enumeration<NetworkInterface> netInterfaces;
		// 拿到所有网卡
		netInterfaces = NetworkInterface.getNetworkInterfaces();
		// 遍历每个网卡，拿到ip
		while (netInterfaces.hasMoreElements()) {
			NetworkInterface ni = netInterfaces.nextElement();
			Enumeration<InetAddress> addresses = ni.getInetAddresses();
			while (addresses.hasMoreElements()) {
				InetAddress ip = addresses.nextElement();
//					if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(':') == -1) {
	            if(!ip.isLoopbackAddress() && ip instanceof Inet4Address){
	                return ip.getHostAddress();
	            }
			}
		}
		//获取不到本机ip，抛出RuntimeException异常
		throw new RuntimeException("获取本机ip失败！");
    }

	
	public static void main(String[] args) {
		try {
			System.out.println(getHostIP());
		} catch (Exception e) {
			e.printStackTrace();
		}       
	}
}
